﻿using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

namespace CaseManagerLibrary.Encrypt
{
    public class BouncyCastleRSAHelper
    {
        private readonly RsaEngine _engine = new RsaEngine();
        private readonly Pkcs1Encoding _encryptor = new Pkcs1Encoding(new RsaEngine());
        private readonly Pkcs1Encoding _decryptor = new Pkcs1Encoding(new RsaEngine());

        // 导入公钥 (X.509格式)
        public void ImportPublicKey(string publicKeyBase64)
        {
            try
            {
                string publicKeyPem = $"-----BEGIN PUBLIC KEY-----\n{publicKeyBase64}\n-----END PUBLIC KEY-----";

                byte[] publicKeyBytes = Encoding.UTF8.GetBytes(publicKeyPem);

                using (var reader = new StreamReader(new MemoryStream(publicKeyBytes)))
                {
                    var pemReader = new PemReader(reader);
                    var publicKeyParams = (RsaKeyParameters)pemReader.ReadObject();

                    _encryptor.Init(true, publicKeyParams);
                    _engine.Init(true, publicKeyParams);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导入公钥失败: " + ex.Message);
            }
        }

        public void ImportPublicKeyPem(string pemFile)
        {
            try
            {
                string publicKeyPem = File.ReadAllText(pemFile);

                byte[] publicKeyBytes = Encoding.UTF8.GetBytes(publicKeyPem);

                using (var reader = new StreamReader(new MemoryStream(publicKeyBytes)))
                {
                    var pemReader = new PemReader(reader);
                    var publicKeyParams = (RsaKeyParameters)pemReader.ReadObject();

                    _encryptor.Init(true, publicKeyParams);
                    _engine.Init(true, publicKeyParams);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导入公钥失败: " + ex.Message);
            }
        }

        // 导入私钥 (PKCS8格式)
        public void ImportPrivateKey(string privateKeyBase64)
        {
            try
            {
                string privateKeyPem = $"-----BEGIN PRIVATE KEY-----\n{privateKeyBase64}\n-----END PRIVATE KEY-----";
                byte[] privateKeyBytes = Encoding.UTF8.GetBytes(privateKeyPem);
                using (var reader = new StreamReader(new MemoryStream(privateKeyBytes)))
                {
                    var pemReader = new PemReader(reader);
                    var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                    if (keyPair == null)
                        throw new Exception("私钥解析失败，返回null");
                    var privateKeyParams = (RsaPrivateCrtKeyParameters)keyPair.Private;
                    _decryptor.Init(false, privateKeyParams);
                    _engine.Init(false, privateKeyParams);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导入私钥失败: " + ex.Message);
            }
        }

        // 加密数据
        public byte[] Encrypt(byte[] data)
        {
            try
            {
                return _encryptor.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("加密失败: " + ex.Message);
            }
        }

        // 解密数据
        public byte[] Decrypt(byte[] encryptedData)
        {
            try
            {
                return _decryptor.ProcessBlock(encryptedData, 0, encryptedData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("解密失败: " + ex.Message);
            }
        }

        // 加密文本
        public string EncryptText(string plainText)
        {
            byte[] dataBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes = Encrypt(dataBytes);
            return Convert.ToBase64String(encryptedBytes);
        }

        // 解密文本
        public string DecryptText(string cipherText)
        {
            byte[] encryptedBytes = Convert.FromBase64String(cipherText);
            byte[] decryptedBytes = Decrypt(encryptedBytes);
            return Encoding.UTF8.GetString(decryptedBytes);
        }

        //// 签名数据
        //public byte[] SignData(byte[] data)
        //{
        //    try
        //    {
        //        var signer = SignerUtilities.GetSigner("SHA256withRSA");
        //        signer.Init(true, _decryptor.GetPrivateParameters());
        //        signer.BlockUpdate(data, 0, data.Length);
        //        return signer.GenerateSignature();
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("签名失败: " + ex.Message);
        //    }
        //}

        //// 验证签名
        //public bool VerifyData(byte[] data, byte[] signature)
        //{
        //    try
        //    {
        //        var signer = SignerUtilities.GetSigner("SHA256withRSA");
        //        signer.Init(false, _encryptor.GetPublicParameters());
        //        signer.BlockUpdate(data, 0, data.Length);
        //        return signer.VerifySignature(signature);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("验证签名失败: " + ex.Message);
        //    }
        //}
    }
}
